package com.gcosc.hly.codejava.controller;

import com.gcosc.hly.codejava.Utils.ExcelUtils;
import com.gcosc.hly.codejava.Utils.RequestContextUtils;
import com.gcosc.hly.codejava.entity.AnswerItem;
import com.gcosc.hly.codejava.params.QueryParams;
import com.gcosc.hly.codejava.result.Result;
import com.gcosc.hly.codejava.service.AnswerItemService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/api/answerItem")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class AnswerItemController {

    private final AnswerItemService answerItemService;

    @GetMapping("/list")
    public Result list(QueryParams params){
        return Result.ok(answerItemService.queryParams(params));
    }

    /**
     * 详情
     * */
    @GetMapping("/detail/{id}")
    public Result detail(@PathVariable int id){
        return Result.ok(answerItemService.getDetail(answerItemService.getById(id)));
    }

    @RequestMapping(value = "/export",produces = "application/octet-stream", method = RequestMethod.GET)
    public void excel(QueryParams params){
        ExcelUtils.export("答题卡",
                answerItemService.queryParams(params).getList(),
                RequestContextUtils.getHttpServletResponse());
    }

    @PostMapping("/save")
    public Result save(@RequestBody AnswerItem answerItem){
        if ("java".equals(answerItem.getType())){
            answerItem.setResult(answerItemService.codeTest(answerItem) ? 1 : 0);
        }
        answerItemService.saveAnswerItem(answerItem);
        return Result.ok();
    }

    @PostMapping("/test")
    public Result test(@RequestBody AnswerItem answerItem){
        boolean result = answerItemService.codeTest(answerItem);
        return Result.ok(new HashMap<String, String>(){{
            put("msg", result ? "测试通过" : "测试未通过");
            put("type", result ? "success" : "error");
        }});
    }

}
